# WebAPI服务管理器 - IIS快速部署脚本
# 需要管理员权限运行

# 检查管理员权限
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Host "错误: 此脚本需要管理员权限运行" -ForegroundColor Red
    Write-Host "请右键选择 '以管理员身份运行 PowerShell' 后重试" -ForegroundColor Yellow
    pause
    exit 1
}

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "WebAPI服务管理器 - IIS部署脚本" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# 配置变量
$projectRoot = $PSScriptRoot
$frontendSiteName = "ScadaServiceManager-Frontend"
$backendSiteName = "ScadaServiceManager-Backend"
$frontendPath = Join-Path $projectRoot "dist"
$backendPath = Join-Path $projectRoot "server"
$frontendPort = 8080
$backendPort = 3001

# 步骤1: 检查必需组件
Write-Host "[1/8] 检查必需组件..." -ForegroundColor Yellow

# 检查IIS
$iisFeature = Get-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole
if ($iisFeature.State -ne "Enabled") {
    Write-Host "  ❌ IIS未安装" -ForegroundColor Red
    Write-Host "  正在安装IIS..." -ForegroundColor Yellow
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole -All -NoRestart
    Write-Host "  ✅ IIS已安装（可能需要重启）" -ForegroundColor Green
} else {
    Write-Host "  ✅ IIS已安装" -ForegroundColor Green
}

# 检查WebSocket支持
$wsFeature = Get-WindowsOptionalFeature -Online -FeatureName IIS-WebSockets
if ($wsFeature.State -ne "Enabled") {
    Write-Host "  正在安装WebSocket支持..." -ForegroundColor Yellow
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebSockets -NoRestart
    Write-Host "  ✅ WebSocket支持已安装" -ForegroundColor Green
} else {
    Write-Host "  ✅ WebSocket支持已安装" -ForegroundColor Green
}

# 检查Node.js
$nodePath = "C:\Program Files\nodejs\node.exe"
if (Test-Path $nodePath) {
    $nodeVersion = & $nodePath --version
    Write-Host "  ✅ Node.js已安装 ($nodeVersion)" -ForegroundColor Green
} else {
    Write-Host "  ❌ Node.js未安装或未安装在默认路径" -ForegroundColor Red
    Write-Host "  请安装Node.js 20.19.0或更高版本到默认路径" -ForegroundColor Yellow
    pause
    exit 1
}

Write-Host ""

# 步骤2: 构建项目
Write-Host "[2/8] 构建项目..." -ForegroundColor Yellow

# 构建前端
Write-Host "  正在构建前端..." -ForegroundColor Cyan
Set-Location $projectRoot
& npm run build
if ($LASTEXITCODE -ne 0) {
    Write-Host "  ❌ 前端构建失败" -ForegroundColor Red
    pause
    exit 1
}
Write-Host "  ✅ 前端构建成功" -ForegroundColor Green

# 构建后端
Write-Host "  正在构建后端..." -ForegroundColor Cyan
Set-Location (Join-Path $projectRoot "server")
& npm run build
if ($LASTEXITCODE -ne 0) {
    Write-Host "  ❌ 后端构建失败" -ForegroundColor Red
    pause
    exit 1
}
Write-Host "  ✅ 后端构建成功" -ForegroundColor Green
Set-Location $projectRoot

Write-Host ""

# 步骤3: 检查web.config
Write-Host "[3/8] 检查配置文件..." -ForegroundColor Yellow

$frontendWebConfig = Join-Path $frontendPath "web.config"
if (Test-Path $frontendWebConfig) {
    Write-Host "  ✅ 前端web.config存在" -ForegroundColor Green
} else {
    Write-Host "  ⚠️  前端web.config不存在，将在下次构建时自动复制" -ForegroundColor Yellow
}

$backendWebConfig = Join-Path $backendPath "web.config"
if (Test-Path $backendWebConfig) {
    Write-Host "  ✅ 后端web.config存在" -ForegroundColor Green
} else {
    Write-Host "  ❌ 后端web.config不存在" -ForegroundColor Red
}

Write-Host ""

# 步骤4: 创建/更新前端站点
Write-Host "[4/8] 配置前端IIS站点..." -ForegroundColor Yellow

# 检查站点是否存在
$existingSite = Get-Website -Name $frontendSiteName -ErrorAction SilentlyContinue
if ($existingSite) {
    Write-Host "  站点已存在，正在更新..." -ForegroundColor Cyan
    Stop-Website -Name $frontendSiteName
    Remove-Website -Name $frontendSiteName
    Remove-WebAppPool -Name $frontendSiteName
}

# 创建应用程序池
New-WebAppPool -Name $frontendSiteName | Out-Null
Set-ItemProperty "IIS:\AppPools\$frontendSiteName" -Name managedRuntimeVersion -Value ""
Write-Host "  ✅ 应用程序池已创建" -ForegroundColor Green

# 创建网站
New-Website -Name $frontendSiteName `
    -PhysicalPath $frontendPath `
    -ApplicationPool $frontendSiteName `
    -Port $frontendPort | Out-Null
Write-Host "  ✅ 网站已创建" -ForegroundColor Green

# 设置权限
$acl = Get-Acl $frontendPath
$identity = "IIS AppPool\$frontendSiteName"
$fileSystemRights = [System.Security.AccessControl.FileSystemRights]"ReadAndExecute"
$type = [System.Security.AccessControl.AccessControlType]::Allow
$inheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit"
$propagationFlags = [System.Security.AccessControl.PropagationFlags]::None
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($identity,$fileSystemRights,$inheritanceFlags,$propagationFlags,$type)
$acl.SetAccessRule($accessRule)
Set-Acl $frontendPath $acl
Write-Host "  ✅ 权限已设置" -ForegroundColor Green

Write-Host ""

# 步骤5: 创建/更新后端站点
Write-Host "[5/8] 配置后端IIS站点..." -ForegroundColor Yellow

$existingSite = Get-Website -Name $backendSiteName -ErrorAction SilentlyContinue
if ($existingSite) {
    Write-Host "  站点已存在，正在更新..." -ForegroundColor Cyan
    Stop-Website -Name $backendSiteName
    Remove-Website -Name $backendSiteName
    Remove-WebAppPool -Name $backendSiteName
}

# 创建应用程序池
New-WebAppPool -Name $backendSiteName | Out-Null
Set-ItemProperty "IIS:\AppPools\$backendSiteName" -Name managedRuntimeVersion -Value ""
Write-Host "  ✅ 应用程序池已创建" -ForegroundColor Green

# 创建网站
New-Website -Name $backendSiteName `
    -PhysicalPath $backendPath `
    -ApplicationPool $backendSiteName `
    -Port $backendPort | Out-Null
Write-Host "  ✅ 网站已创建" -ForegroundColor Green

# 启用WebSocket
Set-WebConfigurationProperty -PSPath "IIS:\Sites\$backendSiteName" `
    -Filter "system.webServer/webSocket" `
    -Name "enabled" `
    -Value $true
Write-Host "  ✅ WebSocket已启用" -ForegroundColor Green

# 设置权限
$acl = Get-Acl $backendPath
$identity = "IIS AppPool\$backendSiteName"
$fileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify"
$type = [System.Security.AccessControl.AccessControlType]::Allow
$inheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit"
$propagationFlags = [System.Security.AccessControl.PropagationFlags]::None
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($identity,$fileSystemRights,$inheritanceFlags,$propagationFlags,$type)
$acl.SetAccessRule($accessRule)
Set-Acl $backendPath $acl
Write-Host "  ✅ 权限已设置" -ForegroundColor Green

Write-Host ""

# 步骤6: 启动站点
Write-Host "[6/8] 启动站点..." -ForegroundColor Yellow

Start-Website -Name $frontendSiteName
Start-Website -Name $backendSiteName

Write-Host "  ✅ 站点已启动" -ForegroundColor Green
Write-Host ""

# 步骤7: 验证部署
Write-Host "[7/8] 验证部署..." -ForegroundColor Yellow

Start-Sleep -Seconds 2

# 测试前端
try {
    $response = Invoke-WebRequest -Uri "http://localhost:$frontendPort" -UseBasicParsing -TimeoutSec 5
    if ($response.StatusCode -eq 200) {
        Write-Host "  ✅ 前端访问正常" -ForegroundColor Green
    }
} catch {
    Write-Host "  ⚠️  前端测试失败: $($_.Exception.Message)" -ForegroundColor Yellow
}

# 测试后端
try {
    $response = Invoke-WebRequest -Uri "http://localhost:$backendPort/api/health" -UseBasicParsing -TimeoutSec 5
    if ($response.StatusCode -eq 200) {
        Write-Host "  ✅ 后端API访问正常" -ForegroundColor Green
    }
} catch {
    Write-Host "  ⚠️  后端测试失败: $($_.Exception.Message)" -ForegroundColor Yellow
    Write-Host "  如果使用iisnode，可能需要等待更长时间启动" -ForegroundColor Cyan
}

Write-Host ""

# 步骤8: 显示结果
Write-Host "[8/8] 部署完成" -ForegroundColor Green
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "✅ IIS部署成功！" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "📍 访问地址:" -ForegroundColor Yellow
Write-Host "   前端: http://localhost:$frontendPort" -ForegroundColor White
Write-Host "   后端: http://localhost:$backendPort" -ForegroundColor White
Write-Host ""
Write-Host "🔧 管理命令:" -ForegroundColor Yellow
Write-Host "   查看站点: Get-Website | Where-Object { `$_.Name -like '*ScadaService*' }" -ForegroundColor White
Write-Host "   停止站点: Stop-Website -Name '$frontendSiteName'" -ForegroundColor White
Write-Host "   启动站点: Start-Website -Name '$frontendSiteName'" -ForegroundColor White
Write-Host "   重启池  : Restart-WebAppPool -Name '$frontendSiteName'" -ForegroundColor White
Write-Host ""
Write-Host "📖 详细文档: IIS_DEPLOY.md" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

pause
